// live/apply/index.js
const app = getApp();
const utils = require('../../utils/sharePost.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,//申请id
    startDate: '',
    startTime: '',
    endDate: '',
    endTime: '',
    title: '',
    nickName: '',
    wxId: '',
    showProDialog: false,
    selectedMenuId: 0,
    cateId: 0, //产品标签
    groupId: 0, //195其他分类,375 优惠券商品, 376 套餐商品
    classList: [],
    cardInfo: {},
    userInfo: {},
    Word: '',
    CurrentPage: 1,
    loadingMoreHidden: 1,
    scrollHeight: 500,
    goodsResult: [],
    goodsSelect: [],
    pids: '',
    shareImg: '',
    shareImgSub: '',
    bgImg: '',
    bgImgSub: '',
    productList: [],
    CheckStatus: 0,//待审核，1审核通过，2已拒绝
    LiveQrCode: '',//分享码
    ShareQrCode: '',//开播码
    liveInfo: '',
    remark: '',
    top: 0,
    roomid: 0,
    windowWidth: 375,
    imgHeight: 100,
    priceHeight: 0,
    priceHeight: 0
  },

  submitApply: function () {
    let that = this;
    let title = that.data.title;
    let start = that.data.startDate + " " + that.data.startTime;
    let end = that.data.endDate + " " + that.data.endTime;
    let nickName = that.data.nickName;
    let wxId = that.data.wxId;
    let shareImg = that.data.shareImgSub;
    let bgImg = that.data.bgImgSub;
    let goodsSelect = that.data.goodsSelect;
    let pids = '';
    if (title == '') {
      that.checkWrite('请输入直播标题');
      return;
    }
    if (title.length < 3 || title.length > 17) {
      that.checkWrite('直播标题必须为3-17个字');
      return;
    }
    if (nickName == '') {
      that.checkWrite('请输入主播昵称');
      return;
    }
    if (nickName.length < 2 || nickName.length > 15) {
      that.checkWrite('主播昵称必须为2-15个字');
      return;
    }
    if (wxId == '') {
      that.checkWrite('请输入主播微信账号');
      return;
    }
    let strTime = start.replace(/-/g, "/");
    let endTimes = end.replace(/-/g, "/");
    let mm = new Date(strTime).getTime() - new Date().getTime();
    if (Math.floor(mm / 1000 / 60) < 30) {
      that.checkWrite('所选开播时间至少在30分钟后');
      return;
    }
    let timeEquation = that.getInervalHour(new Date(strTime), new Date(endTimes));
    if (timeEquation < 0) {
      that.checkWrite('结束时间必须大于开始时间');
      return;
    } else if (timeEquation < 0.5) {
      that.checkWrite('开播时间和结束时间间隔不得短于30分钟');
      return;
    } else if (timeEquation > 72) {
      that.checkWrite('所选时间范围必须在72小时以内');
      return;
    }
    if (goodsSelect.length > 0) {
      for (let i = 0; i < goodsSelect.length; i++) {
        if (goodsSelect[i].isSelect == 1) {
          pids += goodsSelect[i].Pid + ',';
        }
      }
      pids = pids.substr(0, pids.length - 1);
    }
    let param = {
      Uid: app.globalData.userInfo.Uid,
      Id: that.data.id,
      Name: title,
      StartTime: start,
      EndTime: end,
      AnchorName: nickName,
      WxId: wxId,
      ShareImg: shareImg,//ShareImg: "https://static.711688.net.cn/upload/adv/ad_2004091442554384624.jpg"
      CoverImg: bgImg,//CoverImg: "https://static.711688.net.cn/upload/adv/ad_2004091443034540535.jpg"
      Pids: pids
    }
    wx.showLoading({
      title: '提交',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/WeApp/ApplyLive',
      data: param,
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wx.showToast({
            title: '提交成功',
          })
          wx.navigateTo({
            url: '../myLiveList/index',
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  getInervalHour: function (startDate, endDate) {
    var ms = endDate.getTime() - startDate.getTime();
    return Math.floor(ms / 1000 / 60 / 60);
  },

  getLastliveInfo: function (id) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/WeApp/GetLive?id=' + id + '&isRefrush=1',
      success: function (res) {
        if (res.data.Data) {
          let liveInfo = res.data.Data.Live;
          let share = liveInfo.ShareImg;
          let bg = liveInfo.CoverImg;
          let shareImg = utils.formatAvater(share, 'https://static.711688.net.cn/upload/adv/');
          let bgImg = utils.formatAvater(bg, 'https://static.711688.net.cn/upload/adv/');
          let productList = res.data.Data.ProductList;
          if (productList && productList.length > 0) {
            for (let i = 0; i < productList.length; i++) {
              productList[i].isSelect = 1;
              if (productList[i].ShowImg.indexOf('ps') != -1) {
                productList[i].ShowImg = utils.formatAvaterByProHead(productList[i].ShowImg);
              } else {
                productList[i].ShowImg = utils.formatAvater(productList[i].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
              }
              // 0：未审核，1：审核中，2:审核通过，3审核失败
              productList[i].StatusName = '';
              if (productList[i].Audit_Status == 0) {
                productList[i].StatusName = '未审核';
              } else if (productList[i].Audit_Status == 1) {
                productList[i].StatusName = '审核中';
              } else if (productList[i].Audit_Status == 2) {
                productList[i].StatusName = '审核通过';
              } else {
                productList[i].StatusName = '审核失败';
              }
            }
          } else {
            productList = [];
          }
          that.setData({
            title: liveInfo.Name,
            wxId: liveInfo.WxId,
            nickName: liveInfo.AnchorName,
            shareImg: shareImg,
            bgImg: bgImg,
            shareImgSub: share,
            bgImgSub: bg,
            Pids: liveInfo.Pids,
            goodsSelect: productList
          })
        }
      }
    })
  },

  // 选择商品
  choosePro: function () {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight - 60
        })
      }
    })
    that.setData({
      showProDialog: !that.data.showProDialog
    })
    that.getAiCardInfo();
  },

  closeProdialog: function () {
    this.setData({
      showProDialog: !this.data.showProDialog
    })
  },
  /** 点击完成按钮是触发 */
  handleConfirm: function (e) {
    this.setData({
      Word: e.detail.value
    })
  },
  /** 搜索框失去焦点是触发 */
  handleBlur: function (e) {
    this.setData({
      Word: e.detail.value
    })
  },
  /** 取消搜索 */
  handleCancel: function (e) {
    this.setData({
      Word: ''
    })
  },
  handleInput: function (e) {
    this.setData({
      Word: e.detail.value
    })
  },
  handleSearchWord: function (e) {
    this.setData({
      CurrentPage: 1,
      loadingMoreHidden: 1,
      goodsResult: []
    })
    this.searchGoods();
  },


  // 选择菜单分类
  selectMenu: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.indexid;
    let cid = e.currentTarget.dataset.cid;
    let gid = e.currentTarget.dataset.gid;
    that.data.CurrentPage = 1;
    that.data.cateId = cid;
    that.data.groupId = gid;
    that.setData({
      selectedMenuId: index,
      goodsResult: []
    })
    that.searchGoods();
  },
  // 加载商品
  searchGoods: function () {
    var that = this;
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    var cardInfo = that.data.cardInfo.CardInfo;
    wx.request({
      url: app.globalData.host + '/api/store/Search',
      data: {
        storeId: app.globalData.storeId,
        groupId: that.data.groupId, //195单品375优惠券376套餐
        cateId: that.data.cateId, //产品标签
        addUid: cardInfo.Uid,
        page: that.data.CurrentPage,
        word: that.data.Word,
        isExtend: 1,
        state: 0,
        isBrokerage: 1
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          var rawData = res.data.Data;
          var products = rawData.ProductList;
          if (that.data.CurrentPage != 1) {
            var preGoods = that.data.goodsResult;
            products = preGoods.concat(products);
          }
          let goodsSelect = that.data.goodsSelect;
          for (let i = 0; i < products.length; i++) {
            if (products[i].SendEndTime.indexOf('1970') != -1) {
              products[i].ExpireTime = '';
            } else {
              products[i].ExpireTime = products[i].SendEndTime.substr(0, products[i].ExpireTime.length - 7);
              products[i].ExpireTime = products[i].SendEndTime.replace(/\//g, "-");
            }
            if (products[i].ShowImg.indexOf('ps') != -1) {
              products[i].ShowImg = utils.formatAvaterByProHead(products[i].ShowImg);
            } else {
              products[i].ShowImg = utils.formatAvater(products[i].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
            }
            products[i].isSelect = 0;
            if (goodsSelect.length > 0) {
              for (let j = 0; j < goodsSelect.length; j++) {
                if (products[i].Pid == goodsSelect[j].Pid) {
                  products[i].isSelect = 1;
                  break;
                }
              }
            }
          }
          that.setData({
            goodsResult: products,
            loadingMoreHidden: rawData.PageModel.TotalPages,
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  choosePid: function (e) {
    let that = this;
    let pid = e.currentTarget.dataset.pid;
    let BrokeragePrice = e.currentTarget.dataset.brokerageprice;
    let goodsResult = that.data.goodsResult;
    let goodsSelect = that.data.goodsSelect;
    if (goodsSelect.length > 4) {
      this.checkWrite('您最多可选择五个商品');
      return;
    }
    for (let i = 0; i < goodsResult.length; i++) {
      if (pid == goodsResult[i].Pid) {
        if (goodsResult[i].isSelect == 0) {
          if (goodsSelect.length > 0) {
            if (BrokeragePrice > 0) {
              if (goodsSelect[0].BrokeragePrice == 0) {
                that.checkWrite('带佣金和不带佣金产品不能混选');
              } else {
                goodsResult[i].isSelect = 1;
                goodsSelect.push(goodsResult[i]);
              }
            } else {
              if (goodsSelect[0].BrokeragePrice > 0) {
                that.checkWrite('带佣金和不带佣金产品不能混选');
              } else {
                goodsResult[i].isSelect = 1;
                goodsSelect.push(goodsResult[i]);
              }
            }
          } else {
            goodsResult[i].isSelect = 1;
            goodsSelect.push(goodsResult[i]);
          }
        } else {
          goodsResult[i].isSelect = 0;
          for (let j = 0; j < goodsSelect.length; j++) {
            if (pid == goodsSelect[j].Pid) {
              that.removeByValue(goodsSelect, pid);
            }
          }
        }
      }
    }
    that.setData({
      goodsSelect: goodsSelect,
      goodsResult: goodsResult
    })
  },
  removeByValue: function (arr, pid) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].Pid == pid) {
        arr.splice(i, 1);
        break;
      }
    }
  },
  choosePidSecond: function (e) {
    let pid = e.currentTarget.dataset.pid;
    let goodsSelect = this.data.goodsSelect;
    for (let i = 0; i < goodsSelect.length; i++) {
      if (pid == goodsSelect[i].Pid) {
        if (goodsSelect[i].isSelect == 0) {
          goodsSelect[i].isSelect = 1;
        } else {
          goodsSelect[i].isSelect = 0;
        }
      }
    }
    this.setData({
      goodsSelect: goodsSelect
    })
  },
  cancelPro: function () {
    this.setData({
      showProDialog: !this.data.showProDialog
    })
  },
  surePro: function () {
    let goodsSelect = this.data.goodsSelect;
    if (goodsSelect.length > 5) {
      that.checkWrite('您最多可选择五个商品');
      return;
    }
    this.setData({
      showProDialog: !this.data.showProDialog
    })
  },
  loadMore: function (e) {
    let that = this;
    let currPage = that.data.CurrentPage;
    if (that.data.loadingMoreHidden > 1 && currPage < that.data.loadingMoreHidden) {
      that.setData({
        CurrentPage: currPage + 1
      })
      that.searchGoods();
    } else {
      return
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.CurentData();
    if (options.lastid > 0) {
      this.getLastliveInfo(options.lastid);
    }
    if (options.id) {
      this.getAppListInfo(options.id);
      this.setData({
        id: options.id
      })
    }
    // 获取屏幕宽度px
    var windowWidth = wx.getSystemInfoSync().windowWidth * 0.88;
    this.setData({
      windowWidth: windowWidth
    })
  },
  getAppListInfo: function (id) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/WeApp/GetLive?id=' + id + '&isRefrush=1',
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            let liveInfo = res.data.Data.Live;
            let share = liveInfo.ShareImg;
            let bg = liveInfo.CoverImg;
            let shareImg = utils.formatAvater(share, 'https://static.711688.net.cn/upload/adv/');
            let bgImg = utils.formatAvater(bg, 'https://static.711688.net.cn/upload/adv/');
            let LiveQrCode = utils.formatAvater(liveInfo.LiveQrCode, 'https://static.711688.net.cn/upload/adv/');//开播码
            let ShareQrCode = utils.formatAvater(liveInfo.ShareQrCode, 'https://static.711688.net.cn/upload/adv/');//分享码
            let remark = '';
            if (liveInfo.remark) {
              remark = liveInfo.remark
            }
            let productList = res.data.Data.ProductList;
            if (productList && productList.length > 0) {
              for (let i = 0; i < productList.length; i++) {
                productList[i].isSelect = 1;
                if (productList[i].ShowImg.indexOf('ps') != -1) {
                  productList[i].ShowImg = utils.formatAvaterByProHead(productList[i].ShowImg);
                } else {
                  productList[i].ShowImg = utils.formatAvater(productList[i].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
                }
                // 0：未审核，1：审核中，2:审核通过，3审核失败
                productList[i].StatusName = '未审核';
                if (productList[i].Audit_Status == 0) {
                  productList[i].StatusName = '未审核';
                } else if (productList[i].Audit_Status == 1) {
                  productList[i].StatusName = '审核中';
                } else if (productList[i].Audit_Status == 2) {
                  productList[i].StatusName = '审核通过';
                } else {
                  productList[i].StatusName = '审核失败';
                }
              }
            } else {
              productList = [];
            }
            that.setData({
              title: liveInfo.Name,
              startDate: liveInfo.StartTime.substr(0, 10),
              startTime: liveInfo.StartTime.substr(11, 8),
              endDate: liveInfo.EndTime.substr(0, 10),
              endTime: liveInfo.EndTime.substr(11, 8),
              wxId: liveInfo.WxId,
              nickName: liveInfo.AnchorName,
              shareImg: shareImg,
              bgImg: bgImg,
              shareImgSub: share,
              bgImgSub: bg,
              CheckStatus: liveInfo.CheckStatus,
              LiveQrCode: LiveQrCode,
              ShareQrCode: ShareQrCode,
              goodsSelect: productList,
              remark: remark
            })
            that.data.roomid = liveInfo.RoomId;
          }
        }

      }
    })
  },
  // 获取名片信息
  getAiCardInfo: function () {
    var that = this;
    var cardId = wx.getStorageSync("cardId")
    if (cardId) {
      wx.request({
        url: app.globalData.host + '/api/BusinessCard/GetAiCard?uid=' + app.globalData.userInfo.Uid + '&staffId=' + cardId,
        success: function (res) {
          if (res.data.Code == 0) {
            that.data.cardInfo = res.data.Data;
            that.getGoodsClassList();
            that.searchGoods();
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false,
            })
          }
        },
      })
    }
  },
  //获取商品分类列表
  getGoodsClassList: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/GetStoreClassList?storeId=' + app.globalData.storeId + "&uid=" + that.data.cardInfo.CardInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            var list = res.data.Data;
            var newList = [];
            var other = [];
            for (let i = 0; i < list.length; i++) {
              list[i].Name = list[i].Name.substr(0, 4);
              if (list[i].StoreCid == 48917) {
                other = list[i];
              } else {
                newList.push(list[i])
              }
            }
            newList = newList.concat(other);
            that.setData({
              classList: newList
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false,
          })
        }
      },
    })
  },

  bindTitle: function (e) {
    var title = e.detail.value;
    this.setData({
      title: title
    })
  },
  bindNickname: function (e) {
    var nickName = e.detail.value;
    this.setData({
      nickName: nickName
    })
  },
  bindWxid: function (e) {
    var wxId = e.detail.value;
    this.setData({
      wxId: wxId
    })
  },

  bindDateChange: function (e) {
    var date = e.detail.value;
    this.setData({
      startDate: date
    })
  },

  bindTimeChange: function (e) {
    var date = e.detail.value + ':00';
    this.setData({
      startTime: date
    })
  },

  bindDateChange2: function (e) {
    var date = e.detail.value;
    this.setData({
      endDate: date
    })
  },

  bindTimeChange2: function (e) {
    var date = e.detail.value + ':00';
    this.setData({
      endTime: date
    })
  },

  chooseUploadImg: function (e) {
    let type = e.currentTarget.dataset.type;//1分享封面图2背景墙
    var that = this;
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths;
        that.uploadimg({
          url: app.globalData.host + '/api/tool/upload?operation=uploadadvertimage', //这里是你图片上传的接口
          path: imgs, //这里是选取的图片的地址数组
          type: type
        });
      },
    })
  },

  // 单图上传
  uploadimg: function (data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[0],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        var str = resp.data
        var pic = JSON.parse(str);
        if (pic.Data == "-3") {
          wx.showToast({
            title: '上传失败',
            mask: true
          })
          return;
        }
        var coverImg = 'https://static.711688.net.cn/upload/adv/' + pic.Data;
        if (data.type == 1) {
          that.setData({
            shareImg: coverImg,
            shareImgSub: pic.Data
          })
        } else {
          that.setData({
            bgImg: coverImg,
            bgImgSub: pic.Data
          })
        }

      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  //图片预览
  preViewImg: function (e) {
    let src = e.currentTarget.dataset.currsrc;
    let urls = [];
    urls.push(src);
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  //填写判断
  checkWrite: function (str) {
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    })
  },
  // 获取当前年月
  CurentData: function () {
    var that = this;
    var now = new Date();
    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日

    // 直播开始时间
    now.setMinutes(now.getMinutes() + 35);//当前时间加20分钟
    var hh = now.getHours(); //时
    var mm = now.getMinutes(); //分
    var ss = now.getSeconds() //秒
    var clock = year + "-";
    if (month < 10)
      clock += "0";
    clock += month + "-";
    if (day < 10)
      clock += "0";
    clock += day + " ";

    var time = '';
    if (hh < 10)
      time += "0";
    time += hh + ":";
    if (mm < 10)
      time += '0';
    time += mm + ':00';
    that.setData({
      startDate: clock,
      startTime: time,
    })

    // 直播结束时间
    now.setHours(now.getHours() + 12);
    var yearend = now.getFullYear(); //年
    var monthend = now.getMonth() + 1; //月
    var dayend = now.getDate(); //日
    var hhend = now.getHours(); //时
    var mmend = now.getMinutes(); //分
    var ssend = now.getSeconds() //秒
    var clockend = yearend + "-";
    if (monthend < 10)
      clockend += "0";
    clockend += monthend + "-";
    if (dayend < 10)
      clockend += "0";
    clockend += dayend + " ";

    var timeend = '';
    if (hhend < 10)
      timeend += "0";
    timeend += hhend + ":";
    if (mmend < 10)
      timeend += '0';
    timeend += mmend + ':00';
    that.setData({
      endDate: clockend,
      endTime: timeend
    })
  },


  // 海报（新版）
  showPost: function (e) {
    let that = this;
    let proImg = e.currentTarget.dataset.img;
    let proinfo = {};
    proinfo.name = e.currentTarget.dataset.name;
    proinfo.price = e.currentTarget.dataset.price;
    proinfo.shadowprice = e.currentTarget.dataset.shadow;
    proinfo.saleCount = e.currentTarget.dataset.salecount;
    that.setData({
      showpost: true
    })
    // 下载产品图片
    if (proImg) {
      wx.downloadFile({
        url: proImg,
        success: function (res) {
          if (res.statusCode === 200) {
            var productSrc = res.tempFilePath;
            that.calculateImg(productSrc, proinfo, function (data) {
              that.getLiveCode(proinfo, productSrc, data);
            })
          } else {
            wx.showToast({
              title: '产品图片下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var productSrc = "";
                that.getLiveCode(proinfo, productSrc);
              }
            })
          }
        }
      })
    } else {
      proinfo.name = '';
      proinfo.price = '';
      proinfo.shadowprice = '';
      wx.downloadFile({
        url: that.data.shareImg,
        success: function (res) {
          if (res.statusCode === 200) {
            var productSrc = res.tempFilePath;
            that.calculateImg(productSrc, "", function (data) {
              that.getLiveCode(proinfo, productSrc, data);
            })
          } else {
            wx.showToast({
              title: '直播分享图片下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var productSrc = "";
                that.getLiveCode(proinfo, productSrc);
              }
            })
          }
        }
      })
    }
  },
  getLiveCode: function (proinfo, productSrc, imgInfo = '') {
    let that = this;
    let ShareQrCode = that.data.ShareQrCode;
    // 下载直播分享码
    wx.downloadFile({
      url: ShareQrCode,
      success: function (res) {
        if (res.statusCode === 200) {
          var liveCode = res.tempFilePath;
          that.getSlideImg(proinfo, productSrc, imgInfo, liveCode);
        } else {
          wx.showToast({
            title: '直播分享码下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var liveCode = "";
              that.getSlideImg(proinfo, productSrc, imgInfo, liveCode);
            }
          })
        }
      }
    })
  },

  getSlideImg: function (proinfo, productSrc, imgInfo, liveCode) {
    let that = this;
    var cardId = wx.getStorageSync("cardId")
    if (cardId) {
      wx.request({
        url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardId,
        success: function (res) {
          if (res.data.Code == 0) {
            let cardInfo = res.data.Data;
            let avaters = res.data.Data.Slides;
            let slider = '';
            if (avaters) {
              avaters = avaters.split(',');
              var ShowImg = utils.formatAvater(avaters[avaters.length - 1], 'https://static.711688.net.cn/upload/card/source/');
              // 下载商家轮播头图
              wx.downloadFile({
                url: ShowImg,
                success: function (res) {
                  slider = res.tempFilePath;
                  that.getAvatar(proinfo, productSrc, imgInfo, liveCode, slider, cardInfo);
                },
                fail: function (res) {
                  that.getAvatar(proinfo, productSrc, imgInfo, liveCode, slider, cardInfo);
                }
              })
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false,
            })
          }
        },
      })
    }
  },
  getAvatar: function (proinfo, productSrc, imgInfo, liveCode, slider, cardInfo) {
    let that = this;
    // let avatar = cardInfo.UserInfo.Avatar;
    let avatar = app.globalData.userInfo.Avatar;
    let avater = '';
    // 下载商家微信头像
    wx.downloadFile({
      url: avatar,
      success: function (res) {
        avater = res.tempFilePath;
        that.sharePosteCanvas(proinfo, productSrc, imgInfo, liveCode, slider, cardInfo, avater);
      },
      fail: function (err) {
        that.sharePosteCanvas(proinfo, productSrc, imgInfo, liveCode, slider, cardInfo, avater);
      }
    })
  },

  //canvas绘制分享海报
  sharePosteCanvas: function (proinfo, productSrc, imgInfo, liveCode, slider, cardInfo, avater) {
    var that = this;
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    const ctx = wx.createCanvasContext('myCanvas', that);
    const query = wx.createSelectorQuery().in(this);
    query.select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var width = rect.width;

      const grd = ctx.createLinearGradient(0, 0, 0, height / 2);
      grd.addColorStop(0, '#FCCA01');
      grd.addColorStop(1, '#FD8417');
      ctx.setFillStyle(grd);
      // ctx.fillRect(0, 0, width, height);

      ctx.save();
      var bw = width;
      var bh = height;
      var bx = 0;
      var by = 0;
      var br = 10;
      ctx.beginPath()
      ctx.moveTo(bx + br, by)
      ctx.arcTo(bx + bw, by, bx + bw, by + bh, br)
      ctx.arcTo(bx + bw, by + bh, bx, by + bh, br)
      ctx.arcTo(bx, by + bh, bx, by, br)
      ctx.arcTo(bx, by, bx + bw, by, br)
      ctx.closePath();
      ctx.clip()
      ctx.fillRect(0, 0, width, height);
      ctx.restore() // 返回上一状态

      if (slider) {
        utils.circleImg(ctx, slider, width * 0.03, 11, 12);
      }
      // 昵称长度：
      let nicknameLength = width - 46 - width * 0.06;
      let nicknameByte = Math.floor(nicknameLength / 15);
      ctx.font = '16px sans-serif';
      ctx.fillStyle = '#000';
      ctx.setTextAlign('left');
      let nickName = that.data.nickName;
      if (nickName.length > nicknameByte) {
        nickName = nickName.substr(0, nicknameByte) + '...';
      }
      ctx.fillText(nickName, width * 0.03 + 35, 28);//姓名

      var imgheght = width * 0.94;
      if (imgInfo) {
        imgheght = parseFloat(imgInfo);
      }
      utils.fillRoundRect(ctx, width * 0.03, 45, width * 0.94, imgheght + that.data.nameHeight + that.data.priceHeight + 23, 4, 'rgba(255, 255, 255, 1)');

      // 产品头图
      if (productSrc) {
        ctx.drawImage(productSrc, 0, 0, width * 0.94, imgheght);
      }

      ctx.font = 'bold 18px sans-serif';
      ctx.fillStyle = '#000';
      let title = that.data.title;

      let titleLength = width - 30 - width * 0.04;
      let titleByte = Math.floor(titleLength / 17);

      const CONTENT_ROW_LENGTH = titleByte * 2; // 正文 单行显示字符长度
      let [contentLeng, contentArray, contentRows] = utils.textByteLength(title, CONTENT_ROW_LENGTH);
      let contentHh = 22 * 1;
      for (let m = 0; m < contentArray.length; m++) {
        ctx.fillText(contentArray[m], width * 0.02, imgheght + 25 + contentHh * m);
      }

      //  产品金额
      let price = proinfo.price;
      ctx.font = 'bold 25px sans-serif';
      ctx.fillStyle = '#FE0909';
      ctx.setTextAlign('left');
      ctx.fillText(price, width * 0.01, imgheght + that.data.nameHeight + 35); //价格

      //优惠政策
      if (proinfo.shadowprice) {
        ctx.font = '12px sans-serif';
        ctx.fillStyle = '#A6A6A6';
        var shadowprice = proinfo.shadowprice;
        ctx.fillText(shadowprice, width * 0.02 + that.data.priceWidth, imgheght + that.data.nameHeight + 34); //优惠政策
      }

      // 销量
      if (proinfo.saleCount > 19) {
        ctx.setTextAlign('left');
        ctx.font = '12px sans-serif';
        ctx.fillStyle = '#A6A6A6';
        var saleCount = '销量：' + proinfo.saleCount;
        if (that.data.priceHeight > 20) {
          ctx.fillText(saleCount, width * 0.02, imgheght + that.data.nameHeight + 52); //销量
        } else {
          ctx.fillText(saleCount, width * 0.02 + that.data.priceWidth + that.data.shadowpriceWidth + 10, imgheght + that.data.nameHeight + 34); //销量
        }
      }

      if (avater) {
        utils.circleImg(ctx, avater, 0, imgheght + that.data.nameHeight + that.data.priceHeight + 40, 12);
      }

      if (cardInfo) {
        let NickName = app.globalData.userInfo.NickName;
        if (NickName.length > 12) {
          NickName = NickName.substr(0, 12) + '...';
        } else {
          NickName = NickName;
        }
        ctx.font = '16px sans-serif';
        ctx.fillStyle = '#FFFFFF';
        ctx.setTextAlign('left');
        ctx.fillText(NickName, 30, imgheght + that.data.nameHeight + that.data.priceHeight + 60);
        ctx.font = '14px sans-serif';
        ctx.fillStyle = '#FFFFFF';
        ctx.setTextAlign('left');
        ctx.fillText('长按识别二维码  去看看 ->', 0, imgheght + that.data.nameHeight + that.data.priceHeight + 88);
      }
      //  直播分享码
      if (liveCode) {
        utils.circleImg(ctx, liveCode, width - 84, imgheght + that.data.nameHeight + that.data.priceHeight + 38, 32, 32);
      }
    }).exec()
    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)
  },



  //监听用户滑动页面事件
  onPageScroll: function (e) {
    let top = parseInt(e.scrollTop);
    if (!this.data.showpost) {
      this.setData({
        top: top
      })
    }
  },
  // 海报分享
  onShareAppMessage: function () {
    var that = this;
    var cardid = wx.getStorageSync("cardId");
    return {
      imageUrl: that.data.shareImg,
      title: that.data.title,
      path: 'plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=' + that.data.roomid + '&custom_params=' + encodeURIComponent(JSON.stringify({
        cardId: cardid,
        saleUid: 0
      })),
      success: function (res) {
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      }
    }
  },

  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  that.closePoste();
                  if (res.confirm) { }
                },
                fail: function (res) {
                }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: '请删掉小程序再重新授权允许保存至相册',
                icon: 'none',
                duration: 2000
              })
            }
          })
        },
        fail: function (err) {
        }
      }, that);
    }, 1000);
  },

  closePoste: function () {
    this.setData({
      showpost: false
    })
  },

  //计算图片尺寸
  calculateImg: function (src, proinfo, cb) {
    var that = this;
    let windowWidth = that.data.windowWidth;
    let title = that.data.title;

    let nameLength = windowWidth - 30 - windowWidth * 0.04;
    let nameByte = Math.floor(nameLength / 17);
    let CONTENT_ROW_LENGTH = 2 * nameByte;
    let [contentLeng, contentArray, contentRows] = utils.textByteLength(title, CONTENT_ROW_LENGTH);//直播标题行数、

    if (proinfo) {
      proinfo.price = '¥' + proinfo.price;
      let priceWidth = proinfo.price.length * 21;
      if (proinfo.price.indexOf('.') != -1) {
        priceWidth = priceWidth - 20;
      }
      let shadowpriceWidth = proinfo.shadowprice.length * 12;
      let saleCountWidth = proinfo.saleCount.toString().length * 12 + 30;
      if (proinfo.saleCount < 20) {
        saleCountWidth = 0;
      }
      let priceHeight = 20;
      if (priceWidth + shadowpriceWidth + saleCountWidth > windowWidth * 0.96 - 20) {
        priceHeight = 40
      }

      that.setData({
        nameHeight: 22 * contentArray.length,
        priceWidth: priceWidth,
        shadowpriceWidth: shadowpriceWidth,
        saleCountWidth: saleCountWidth,
        priceHeight: priceHeight
      })
    } else {
      that.setData({
        nameHeight: 22 * contentArray.length
      })
    }

    wx.getImageInfo({
      src: src,
      success(res) {
        wx.getSystemInfo({
          success(res2) {
            var ratio = res.width / res.height;
            var imgHeight = (res2.windowWidth * 0.85 / ratio) + 130;
            that.setData({ imgHeight: imgHeight })
            cb(imgHeight - 130);
          }
        })
      }
    })
  }
})